import { InferAttributes } from 'sequelize'
import { AccountProxy, redis } from '~/db'

/**
 * 获取公众号消息的代理列表
 */
export async function getAccountProxies(app_id: string) {
    //先尝试通过redis获取
    const cache = await redis.get(`proxy:${app_id}`)
    if (cache) {
        const rows: InferAttributes<AccountProxy>[] = JSON.parse(cache)
        if (rows && Array.isArray(rows)) {
            return rows.map((row) => new AccountProxy(row, { isNewRecord: true }))
        }
    }

    const rows = await AccountProxy.findAll({
        where: {
            app_id,
            is_enable: 1,
        },
        attributes: ['id', 'proxy_url', 'mode', 'msg_token', 'encoding_aes_key'],
    })

    await redis.set(`proxy:${app_id}`, JSON.stringify(rows.map((t) => t.toJSON())))

    return rows
}
